package hero_summon

import (
	"go_server/game_server/dao/count_down_dao"
	"go_server/game_server/dao/daily_dao"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/game_server/world_manager"
	"go_server/zinx/ziface"
	"go_server/zinx/znet"
	"time"
)

type SummonShowApi struct {
	znet.BaseRouter
}

// 英雄招募
func (*SummonShowApi) Handle(request ziface.IRequest) {
	msg := &pb.SummonShowC2S{}
	if !util.PBParseRet(request, msg) {
		return
	}

	conn := request.GetConnection()
	roleId := ServiceObj.GetRoleId(request)

	drawConfig := config_manager.GetStcTableHeroDraw_SheetDrawList()
	if len(drawConfig) <= 0 {
		world_manager.WorldMgrObj.SendClientErrMsg(roleId, request, pb.ErrorCodeManager_HERO_SUMMON_POOL_NOT_EXIST, nil)
		return
	}

	// 获取当日已使用的免费次数
	dateKey := time.Now().Format("20060102")
	row := daily_dao.GetDailyByDateKey(dateKey, roleId, []string{"hero_summon_use_free_time"})

	heroSummonUseFreeTime := make(map[int32]int32)
	if row != nil && row.HeroSummonUseFreeTime.Data() != nil {
		heroSummonUseFreeTime = row.HeroSummonUseFreeTime.Data()
	}

	// 获取上次使用免费抽次数时间
	row1 := count_down_dao.GetCountDownByRoleId(roleId, []string{"hero_summon_last_time"})

	heroSummonLastTime := make(map[int32]int64)
	if row1 != nil && row1.HeroSummonLastTime.Data() != nil {
		heroSummonLastTime = row1.HeroSummonLastTime.Data()
	}

	summonHeroStateList := make(map[int32]*pb.SummonHeroStateInfo) // 抽取的奖励列表

	for _, typeValue := range SummonTypes {
		summonHeroStateInfo := new(pb.SummonHeroStateInfo)
		var remainFreeTimes = drawConfig[typeValue].FreeNum // 剩余免费次数
		var refreshTime int64 = 0                           // 下次使用免费抽奖时间，新人为 0

		hadUseTimes, exist := heroSummonUseFreeTime[typeValue]
		if exist {
			if hadUseTimes >= drawConfig[typeValue].FreeNum {
				remainFreeTimes = 0
			} else {
				remainFreeTimes = drawConfig[typeValue].FreeNum - hadUseTimes
			}
		}

		lastTime, exist1 := heroSummonLastTime[typeValue]
		if exist1 {
			// 获取次日凌晨零点的时间戳，单位毫秒
			timeStr := time.Now().Format("2006-01-02")
			t2, _ := time.ParseInLocation("2006-01-02", timeStr, time.Local)
			nextDayTime := t2.AddDate(0, 0, 1).UnixMilli()

			// 下次刷新时间超过次日0点
			if (lastTime + int64(drawConfig[typeValue].Time*1000)) >= nextDayTime {
				refreshTime = lastTime + int64(drawConfig[typeValue].Time*1000)
			} else {
				// 未超过次日0点，则判断当日免费次数是否使用完
				if remainFreeTimes <= 0 { // 今日剩余免费次数为0
					refreshTime = nextDayTime // 下次刷新时间为次日0点
				} else {
					refreshTime = lastTime + int64(drawConfig[typeValue].Time*1000)
				}
			}
		}

		summonHeroStateInfo.RefreshTime = refreshTime
		summonHeroStateInfo.RemainFreeTimes = remainFreeTimes
		summonHeroStateList[typeValue] = summonHeroStateInfo
	}

	res := &pb.SummonShowS2C{
		SummonHeroStateList: summonHeroStateList,
	}

	// 优先返回下行
	conn.SendBuffPBMsg(uint32(pb.ProtocolManager_SummonShow), res)
}
